package com.aifast.system.sys.service;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.global.BusinessException;
import com.aifast.common.global.Const;
import com.aifast.system.sys.dao.SysUserDao;
import com.aifast.system.sys.entity.SysRole;
import com.aifast.system.sys.entity.SysUser;
import com.aifast.system.sys.entity.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author fujian
 * @since 2022/1/16 10:53
 */
@Component
@RequiredArgsConstructor
public class StpInterfaceService implements StpInterface {

    private final SysUserDao sysUserDao;
    private final SysOrgService sysOrgService;
    private final SysRoleService sysRoleService;
    @Value("${ai.tenant.enable}")
    private boolean tenantEnable = false;


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuthorities(loginId);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getRoles(loginId);
    }

    /**
     * 获取当前用户所有角色的权限代码
     * @return
     */
    private List<String> getAuthorities(Object loginId) {
        UserInfo userInfo = UserInfo.get(Convert.toStr(loginId));
        if (ObjectUtil.isNull(userInfo)) {
            userInfo = createCurrentUserInfo(sysUserDao.selectById(Convert.toInt(loginId)));
        }
        if (StrUtil.equals("1", userInfo.getAdmin())) {
            userInfo.getAuthorities().add(Const.WILDCARD);
        }
        return userInfo.getAuthorities();

    }

    /**
     * 获取当前用户所有角色的code集合
     * @return
     */
    private List<String> getRoles(Object loginId){
        UserInfo userInfo = UserInfo.get(Convert.toStr(loginId));
        if(ObjectUtil.isNull(userInfo)){
            userInfo = createCurrentUserInfo(sysUserDao.selectById(Convert.toInt(loginId)));
        }
        return userInfo.getRoles().stream().map(SysRole::getCode).filter(i-> StrUtil.isNotBlank(i)).collect(Collectors.toList());
    }

    /**
     * 创建缓存
     * @param one
     */
    public UserInfo createCurrentUserInfo(SysUser one) {
        try {
            if (tenantEnable && StpUtil.isLogin()) {
                StpUtil.getSession().set("tenantId", one.getTenantId());
            }
            return UserInfo.init(one, sysOrgService.info(one.getOrgId())
                    , sysRoleService.getRoles(one.getId())
                    , sysRoleService.getAuthorities(one.getId()));
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("用户信息不完整，获取用户信息失败，相关操作将无法进行");
        }
    }

}
